<template>
  
	  <!-- 头像 -->
	  <view class="my-header">
		  <view class="my-header_background">
			  <image :src="imgsrc" mode=""></image>
		  </view>
		  <view class="my-header_logo">
			  <view class="my-header_logo-box">
				  <image :src="imgsrc" mode="aspectFill" @click="imgclick()"></image>
			  </view>
		     <view class="my-header_name"@click="editName">{{this.nickname}}</view>
				  <text class="my-header_age">年龄：{{this.age}}</text>
			      <text class="my-header_gender">性别：{{this.gender}}</text>
		  </view>

	  </view>
	  <view class="my-content">
		  <view class="my-content_list">
		  			  <view class="my-content_list-title" @click="showPersonalData">
		  				  <uni-icons clss="icons" type="home-filled" size="24" color="#666"style="margin-right: 10rpx;"></uni-icons>
		  				  <text>个人身材数据</text>
		  			  </view>
		  			  <uni-icons type="arrowright" size="20" color="#666"></uni-icons>
		  </view>
		  <view class="my-content_list">
		  			  <view class="my-content_list-title" @click="showCollection">
		  				  <uni-icons clss="icons" type="star" size="24" color="#666" style="margin-right: 10rpx;"></uni-icons>
		  				  <text>我的收藏</text>
		  			  </view>
		  			  <uni-icons type="arrowright" size="20" color="#666"></uni-icons>
		  </view>
		  <view class="my-content_list">
		  			  <view class="my-content_list-title" @click="goToFeedbackPage">
		  				  <uni-icons clss="icons" type="contact" size="24" color="#666"style="margin-right: 10rpx;"></uni-icons>
		  				  <text>隐私设置</text>
		  			  </view>
					  <switch :checked="isPrivacyEnabled" @change="togglePrivacy" color="#FFC90E" style="transform:scale(0.7)"/>
		  			  <!-- <uni-icons type="arrowright" size="14" color="#666"></uni-icons> -->
					  
		  </view>
		  <!-- 动态显示选项 -->
		  <view v-if="isPrivacyEnabled" class="privacy-options">
		 		<view class="option">
		 		    <radio-group @change="handleSetChange">
		 				<view class="optin-text">
		 					<radio color="#FFC90E" style="transform:scale(0.7);"></radio>
		 					 <view style="">仅个人推荐</view>
		 				</view>
		 				<view class="optin-text">
		 						  <radio color="#FFC90E"style="transform:scale(0.7);"></radio>
		 						   <view style="">允许品牌分析</view>
		 				 </view>
		 			</radio-group>
		 		</view>
		   </view>
		  
		  <view class="my-content_list">
		    <view class="my-content_list-title" @click="goToFeedbackPage">
		      <uni-icons class="icons" type="help" size="24" color="#666"style="margin-right: 10rpx;"></uni-icons>
		      <text>意见反馈</text>
		    </view>
		    <uni-icons type="arrowright" size="20" color="#666"></uni-icons>
		  </view>
		  <view class="my-content_list">
		  	 <view class="my-content_list-title1"@click="loginPage">
		  		  <uni-icons clss="icons" type="arrow-right" size="24" color="#666"style="margin-right: 10rpx;"></uni-icons>
		  		  <text>退出登录</text>
		  	 </view>
		  </view>
	  </view>
</template>

<script>
import axios from "axios"
import setting from "../../setting"

export default {
  data() {
    return {
      imgsrc: "/static/new_logo.jpg",
      nickname: "defualt_name",
      isPrivacyEnabled: false, // 隐私设置开关状态
      privacyRadio: "",
      name: "",
      age: 18,
      gender: "女",
      clothingSize: "",
      feedback: "",
      height: "",
      weight: "",
      skinColor: "",
      complexion: "",
      hairQuality: "",
      eyeColor: "",
      gums: "",
      isPersonalDataVisible: false,
      userId: 0,
    }
  },

  onShow() {
    const userId = uni.getStorageSync("user_id")
    if (userId) {
      this.userId = userId
      this.fetchUserInfo(userId) // 调用异步函数
      console.log(userId) // 这行会立即执行
    } else {
      console.error("未找到用户ID")
    }
  },
  methods: {
    togglePrivacy(e) {
      this.isPrivacyEnabled = e.detail.value
    },
    handleSetChange(e) {
      this.privacyRadio = e.detail
    },
    fetchUserInfo(userId) {
      return uni
        .request({
          method: "GET",
          url: `${setting.url}/api/user-info`,
          data: {
            user_id: userId, // 将 user_id 参数传递到请求中
          },
        })
        .then((response) => {
          const data = response.data
          console.log(data)
          this.fetchUser_file_id(userId) // 调用其他方法
          // 更新 Vue 实例的数据
          this.nickname = data.nickname
          this.age = data.age
          this.gender = data.gender
        })
        .catch((error) => {
          console.log("获取用户信息失败:", error)
          throw error // 将错误继续抛出，以便外部捕获
        })
    },
    
    // 修改后的头像选择方法
    imgclick() {
      uni.showLoading({
        title: "准备中...",
        mask: true,
      })
      
      // 使用uni.chooseImage的简化版本，避免复杂的文件处理逻辑
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 允许从相册选择或拍照
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          console.log("选择的图片路径:", tempFilePath)
          
          // 直接使用uni.uploadFile上传文件
          this.uploadAvatarDirectly(tempFilePath)
        },
        fail: (err) => {
          console.error("选择图片失败:", err)
          uni.hideLoading()
          uni.showToast({
            title: "选择图片失败",
            icon: "none",
            duration: 2000
          })
        }
      })
    },
    
    // 直接上传文件的方法
    uploadAvatarDirectly(filePath) {
      uni.uploadFile({
        url: `${setting.url}/api/upload-avatar`,
        filePath: filePath,
        name: 'file',
        formData: {
          'user_id': this.userId
        },
        success: (uploadRes) => {
          console.log("上传响应:", uploadRes)
          
          // 解析响应数据
          let responseData
          try {
            responseData = JSON.parse(uploadRes.data)
          } catch (e) {
            console.error("解析响应数据失败:", e)
            responseData = { message: "响应数据格式错误" }
          }
          
          if (uploadRes.statusCode === 200 && responseData.file_id) {
            // 更新头像显示
            let fileUrl = responseData.file_id
            
            // 确保URL是完整的
            if (fileUrl && !fileUrl.startsWith('http') && !fileUrl.startsWith('/static/')) {
              this.imgsrc = `${setting.url}${fileUrl}`
            } else {
              this.imgsrc = fileUrl
            }
            
            console.log("设置的头像URL:", this.imgsrc)
            
            uni.showToast({
              title: "头像上传成功",
              icon: "success",
              duration: 2000
            })
          } else {
            uni.showToast({
              title: responseData.message || "上传失败",
              icon: "none",
              duration: 2000
            })
          }
        },
        fail: (error) => {
          console.error("上传失败:", error)
          uni.showToast({
            title: "上传失败，请检查网络",
            icon: "none",
            duration: 2000
          })
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },
    
    // 修改 fetchUser_file_id 方法，添加完整的服务器地址
    fetchUser_file_id(userId) {
      return uni
        .request({
          method: "GET",
          url: `${setting.url}/api/get-file-id`,
          data: {
            user_id: userId, // 将 user_id 参数传递到请求中
          },
        })
        .then((response) => {
          const data = response.data
          console.log("获取到的头像数据:", data)
          
          // 检查file_id是否为完整URL
          if (data.file_id) {
            if (data.file_id.startsWith('/static/')) {
              // 静态资源路径保持不变
              this.imgsrc = data.file_id
            } else if (!data.file_id.startsWith('http')) {
              // 如果是相对路径，添加服务器地址前缀
              this.imgsrc = `${setting.url}${data.file_id}`
            } else {
              // 如果已经是完整URL，直接使用
              this.imgsrc = data.file_id
            }
          } else {
            // 如果没有头像，使用默认头像
            this.imgsrc = "/static/new_logo.jpg"
          }
          
          console.log("最终使用的头像URL:", this.imgsrc)
        })
        .catch((error) => {
          console.log("获取头像信息失败:", error)
          this.imgsrc = "/static/new_logo.jpg" // 出错时使用默认头像
          throw error // 将错误继续抛出，以便外部捕获
        })
    },
    
    loginPage() {
      uni.redirectTo({
        url: "/pages/login/login",
      })
    },
    showPersonalData() {
      uni.navigateTo({
        url: "/pages/data-page/data-page",
      })
    },
    showCollection() {
      uni.navigateTo({
        url: "/pages/Collection/Collection",
      })
    },
    goToFeedbackPage() {
      uni.navigateTo({
        url: "/pages/feedback/feedback", // 跳转到意见反馈页面
      })
    },
    editName() {
      console.log("编辑昵称")
    },
  },
}
</script>

<style lang="scss">
	page{background-color: #f5f5f5;}
.my-header{
	position: relative;
	padding-bottom: 15px;
	.my-header_background{
		position: absolute;
		top:0;
		right: 0;
		bottom: 0;
		left: 0;
		filter: blur(8px);
		opacity: 0.3;
		image{
			width: 100%;
			height:100%;
		}
	}
	.my-header_logo{
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 30px;
		
		.my-header_logo-box{
			width: 60px;
			height: 60px;
			border-radius: 50%;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
				
			}
		}
		.my-header_name{
			margin-top: 15px;
			font-size: 26rpx;
			font-weight: bold;
		}
		.my-header_age{
			margin-top: 10px;
			font-size: 26rpx;
			
		}
		.my-header_gender{
			margin-top: 10px;
			font-size: 26rpx;
		}
		
	}

}
.my-content{
	.my-content_list{
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		margin-bottom: 10px;
		height: 25px;
		background-color: #FFFFFF;
		color: #333;
		font-size: 28rpx;
		.my-content_list-title{
			display: flex;
			align-items: center;
			.icons{
				margin-right: 5rpx;
			}
		}
		.my-content_list-title1{
			display: flex;  
			align-items: center;
		}
	}
}
.container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */  
  margin-bottom: 10px; /* 每组输入框之间的间距 */
  justify-content: space-around;
  padding: 10px;
  background-color: #fefefe; /* 浅黄色背景 */
}
.label {  
	display: flex;
  font-size: 10px; /* 可选：设置字体大小 */  
  width: 60px; /* 设置标签的宽度 */  
  margin-right: 10px; /* 标签和输入框之间的间距 */  
}  
.option{
	display: flex;
	margin-bottom: 5px;
	margin-left: 8px;
}

.optin-text{
	font-size: 13px;
	display: flex;
	flex-direction: row;
}
.input {  
  
  flex-grow: 1; /* 输入框占据剩余空间 */  
  height: 15px; /* 设置输入框高度 */  
  border: 1px solid #ccc; /* 边框样式 */  
  border-radius: 4px; /* 圆角 */  
  padding: 5px; /* 内边距 */  
}  
.personal-info, .detailed-data {
  width: 45%;
}


.section {
	display: flex;
	width: 150px; /* 设置宽度 */  
	height: 30px; /* 设置高度 */  
	padding: 5px; /* 设置内边距 */  
	 
	border-radius: 4px; /* 可选：设置圆角 */  
   //margin-bottom: 5px;
}
.section1 {
	display: flex;
	padding: 5px; /* 设置内边距 */ 
	font-size: 13px;
  margin-bottom: 5px;
}
.data-item {
  margin-bottom: 5px;
}

input, textarea {

  padding: 5px;
  border-radius: 4px;
}
</style>